package com.dfd.mango.admin.service.impl;

import com.dfd.mango.admin.entity.SysCaptcha;
import com.dfd.mango.admin.mapper.SysCaptchaMapper;
import com.dfd.mango.admin.service.SysCaptchaService;
import com.dfd.mango.common.DateTimeUtils;
import com.dfd.mango.common.StringUtils;
import com.dfd.mango.core.exception.MangoException;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

@Service
public class SysCaptchaServiceImpl implements SysCaptchaService {
    @Autowired
    private Producer producer;
    @Autowired
    private SysCaptchaMapper sysCaptchaMapper;

    /**
     * 生成验证码
     * @param uuid
     * @return
     */
    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new MangoException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha sysCaptcha = new SysCaptcha();
        sysCaptcha.setUuid(uuid);
        sysCaptcha.setCode(code);
        //5分钟后过期
        sysCaptcha.setExpireTime(DateTimeUtils.addDateMinutes(new Date(), 5));
        this.insert(sysCaptcha);
        return producer.createImage(code);
    }

    @Override
    public int deleteByPrimaryKey(String uuid) {
        return sysCaptchaMapper.deleteByPrimaryKey(uuid);
    }

    @Override
    public int insert(SysCaptcha record) {
        return sysCaptchaMapper.insert(record);
    }

    @Override
    public int insertSelective(SysCaptcha record) {
        return sysCaptchaMapper.insertSelective(record);
    }

    @Override
    public SysCaptcha selectByPrimaryKey(String uuid) {
        return sysCaptchaMapper.selectByPrimaryKey(uuid);
    }

    @Override
    public int updateByPrimaryKeySelective(SysCaptcha record) {
        return sysCaptchaMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(SysCaptcha record) {
        return sysCaptchaMapper.updateByPrimaryKey(record);
    }

    @Override
    public boolean validate(String uuid, String captcha) {
        SysCaptcha sysCaptcha = this.selectByPrimaryKey(uuid);

        if (sysCaptcha == null) {
            return false;
        }

        //删除验证码
        this.deleteByPrimaryKey(uuid);

        if (sysCaptcha.getCode().equalsIgnoreCase(captcha) && sysCaptcha.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }

        return false;
    }

    @Override
    public boolean deleteCaptcha() {
        return sysCaptchaMapper.deleteCaptcha();
    }
}

